﻿////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// <copyright>Copyright 2008-2011 Andreas Huber Doenni</copyright>
// Distributed under the GNU General Public License version 2 (GPLv2).
// See accompanying file License.txt or copy at http://phuse.codeplex.com/license.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

namespace Phuse.Mime
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics.CodeAnalysis;
    using System.IO;
    using System.Text;

    using Phuse.IO;
    using Phuse.Text;

    /// <summary>Represents an entity body (see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a> 2.4. &amp;
    /// 2.6.) that contains multiple parts (see <a href="http://www.ietf.org/rfc/rfc2046.txt">RFC 2046</a> 5.1.).
    /// </summary>
    /// <threadsafety static="true" instance="false"/>
    public sealed class MultipartBody : Body<MultipartBody>
    {
        private readonly Guid boundaryGuid = Guid.NewGuid();
        private string preamble = string.Empty;
        private readonly List<BodyPart> parts = new List<BodyPart>();
        private string epilogue = string.Empty;

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        /// <summary>Initializes a new instance of the <see cref="MultipartBody"/> class.</summary>
        /// <param name="subtype">The subtype of the multipart body, usually one of the
        /// <see cref="MultipartSubtypeNames"/> members.</param>
        /// <exception cref="ArgumentException"><paramref name="subtype"/> is <c>null</c> or empty.</exception>
        public MultipartBody(string subtype) : base(subtype)
        {
        }

        /// <summary>Gets or sets the preamble.</summary>
        /// <remarks>The default value is <see cref="string.Empty">string.Empty</see>, which is set during construction
        /// and when the parser does not find a valid preamble.</remarks>
        /// <exception cref="ArgumentNullException">Attempted to set to <c>null</c>.</exception>
        public string Preamble
        {
            get
            {
                return this.preamble;
            }

            set
            {
                if (value == null)
                {
                    throw new ArgumentNullException("value");
                }

                this.preamble = value;
            }
        }

        /// <summary>Gets a collection containing all parts.</summary>
        public IList<BodyPart> Parts
        {
            get { return this.parts; }
        }

        /// <summary>Gets the epilogue.</summary>
        /// <remarks>The default value is <see cref="string.Empty">string.Empty</see>, which is set during construction
        /// and when the parser does not find a valid epilogue.</remarks>
        /// <exception cref="ArgumentNullException">Attempted to set to <c>null</c>.</exception>
        public string Epilogue
        {
            get
            {
                return this.epilogue;
            }

            set
            {
                if (value == null)
                {
                    throw new ArgumentNullException("value");
                }

                this.epilogue = value;
            }
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        internal MultipartBody(FallbackReason fallbackReason) : base(MultipartSubtypeNames.Mixed, fallbackReason)
        {
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        /// <summary>See <see cref="Body.WriteTo(Stream, Action{IEnumerable{HeaderField}, bool})"/>.</summary>
        [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", Justification = "Not callable from external code, CA bug?")]
        protected internal sealed override void WriteTo(
            Stream stream, Action<IEnumerable<HeaderField>, bool> writeHeaderFieldsCallback)
        {
            var boundary = this.boundaryGuid.ToString("N");
            var closeDelimiter = EncodingObjects.ASCII.GetBytes("\r\n--" + boundary + "--");
            var delimiterLength = closeDelimiter.Length - 2;

            var additionalParameters =
                new[] { new KeyValuePair<string, string>(ContentTypeParameterNames.Boundary, boundary) };
            var fields = this.GetRequiredHeaderFields(
                MediaTypeNames.Multipart, additionalParameters, ContentTransferEncodingNames.SevenBit);
            writeHeaderFieldsCallback(fields, true);

            if (stream != null)
            {
                Write(stream, this.preamble, EncodingObjects.ASCII);

                foreach (var part in this.parts)
                {
                    stream.Write(closeDelimiter, 0, delimiterLength);

                    if ((part.Fields.Count > 0) || (part.Body != null))
                    {
                        StreamHelper.WriteLineBreak(stream);
                    }

                    part.WriteToImpl(stream, stream);
                }

                stream.Write(closeDelimiter, 0, closeDelimiter.Length);

                if (!string.IsNullOrEmpty(this.epilogue))
                {
                    StreamHelper.WriteLineBreak(stream);
                }

                Write(stream, this.epilogue, EncodingObjects.ASCII);
            }
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        private static void Write(Stream stream, string text, Encoding encoding)
        {
            var encoded = encoding.GetBytes(text);
            stream.Write(encoded, 0, encoded.Length);
        }
    }
}
